<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class Setup2Form extends MiniyunViewForm
{

	public  $dbName;	public  $userName;	public  $userPasswd;	public  $dbHost;	public  $tablePrefix;	public  $base;	private $_db;	function myErrorHandler($errno, $errstr, $errfile, $errline) {
		if(!$this->hasErrors()){
			$this->addError("dbName", "数据库连接账号或密码设置错误，请检查");
		}
		return true;
	}
	public function init(){
		set_error_handler( array( &$this, 'myErrorHandler' ) );
		$this->dbName="miniyun";
		$this->userName = "miniyun";
		$this->userPasswd = "miniyun";
		$this->dbHost = "127.0.0.1";
		$this->tablePrefix = "miniyun";
		$this->base = dirname(__FILE__)."/../../../upload/";	}
	public function rules()
	{
		$valid = array(
		array('dbName, userName, userPasswd, dbHost,tablePrefix,base', 'required'),
		);
		return $valid;
	}
	public function attributeLabels()
	{ 		return  array(
            'dbName'=>'数据库名',
            'userName'=>'用户名',
            'userPasswd'=>'密码',
            'dbHost'=>'数据库主机',
            'tablePrefix'=>'表名前缀',
		    'base'=>'文件存储路径',
		);
	}

	private  function _checkBase(){
		if(file_exists($this->base)){
			if(is_dir($this->base)){
				if(is_writable($this->base)){
					return true;
				}
			}
		}
		$this->addError('base','文件存储路径不存在或目录无写权限。');
		return false;
	}
	
	private function _baseValidate(){
		if($this->_checkBase()==false){
			return false;
		}
		$success = true;
		$this->_db = mysql_connect($this->dbHost, $this->userName, $this->userPasswd,true);
		if($this->hasErrors()==false){
			if(!mysql_select_db($this->dbName,$this->_db)){
				$this->addError("dbName", "没有访问数据库".$this->dbName."的权限或它不存在<br>请您先创建一个数据库。");
				$success = false;
			}
		}
		if($this->hasErrors()==false){
			$result = mysql_query("show tables from ".$this->dbName,$this->_db);
			while ($row = mysql_fetch_row($result)) {
				$tableName = $row[0];
				$pos = strpos($tableName,$this->tablePrefix);
				if(!is_bool($pos) && $pos==0){
					$this->addError("dbName", "数据库已经存在相关表，请更换一个数据库。<br>或者您可直接编辑miniyun-config.php");
					$success = false;
					break;
				}
			}
		}
		return $success;
	}
	
	private function _initDbConfigFile(){
		$filePath   = dirname(__FILE__).'/../../config/miniyun-config-simple.php';
		
		$content = "";
		$fileHandle = fopen($filePath, "rb");
		while (!feof($fileHandle) ) {
			$content = $content.fgets($fileHandle);
		}
		
		$this->base = str_replace("\\", "/", $this->base);
		fclose($fileHandle);
		$content = str_replace("#dBName#",$this->dbName,$content);
		$content = str_replace("#dBUser#",$this->userName,$content);
		$content = str_replace("#dBPasswd#",$this->userPasswd,$content);
		$content = str_replace("#dBHost#",$this->dbHost,$content);
		$content = str_replace("#tablePrefix#",$this->tablePrefix,$content);
		$content = str_replace("#key#",CUtils::genRandomString(),$content);
		$content = str_replace("#base#",$this->base,$content);
		$filePath = dirname(__FILE__).'/../../config/miniyun-config.php';
		$fh = fopen($filePath, 'w');
		fwrite($fh, $content);
		fclose($fh);
		
		$configPath = dirname(__FILE__).'/../../config/config.php';
		$content    = file_get_contents($configPath);
		$start      = strpos($content,'define');
        $end        = strpos($content,');');
        $search     = substr($content, $start, $end-5);
        $replace    = 'define(\'DB_PASSWORD\', \''.$this->userPasswd.'\');';
		$content    = str_replace($search,$replace,$content);
		file_put_contents($configPath, $content);
	}
	public function save(){
		$success = false;
		if($this->validate()){
			if($this->_baseValidate()){
				if(!$this->hasErrors()){										$sqlPath = dirname(__FILE__).'/../../data/schema.mysql.sql';
					$content = "";
					$fileHandle = fopen($sqlPath, "rb");
					while (!feof($fileHandle) ) {
						$content = $content.fgets($fileHandle);
					}
					fclose($fileHandle);
					$content = str_replace("miniyun_", $this->tablePrefix."_",$content);					$sqls = preg_split("/;/", $content);
					
			        			        			        					mysql_query("set names charset utf8");
                    mysql_query("set names utf8");
					foreach($sqls as $index=>$sql){
						$result = mysql_query($sql);					}
					if(isset($this->_db)){
						mysql_close($this->_db);
					}
										$this->_initDbConfigFile();
					$success =  true;
				}
			}
		}
		if(isset($this->_db)){
			mysql_close($this->_db);
		}
		return $success;
	}
}